package com.javazyw.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.javazyw.annotation.Retry;

/**
 * <p>.</p>
 *
 * @version 
 * @author dongdh
 * @date 2015年7月10日
 *
 */
public class RetryProxy implements InvocationHandler {

	private Object object ;
	
	
	public <T> T getInstance(T t) {
        object = t;
        return (T) Proxy.newProxyInstance(t.getClass().getClassLoader(), 
        		t.getClass().getInterfaces(), this);
    }
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		
		Retry retry = method.getAnnotation(Retry.class);
		Object ret = null;
		if (retry != null) {
		
			int times = retry.times();
			int sleep = retry.sleep();
			
			while (times-- > 0) {
				try {
					ret = method.invoke(object, args);
					break;
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("retry...times=" + times);
					Thread.sleep(sleep);
				}
			}
		} else {
			return method.invoke(object, args);
		}
		return ret;
	}

	public static void main(String[] args) {
		/*final TestService ts = new RetryProxy().getInstance(new TestServiceImpl());
		
		Thread t = new Thread(new  Runnable() {
			public void run() {
				ts.test("aaa");
			}
		});
		t.start();

		System.out.println("===============>>>");*/
	}
}
